import React, { Component } from 'react';
import {
	StyleSheet, Text, View, Image, TouchableOpacity,
	PixelRatio, FlatList
} from "react-native";
import { API, API_GENERATE } from '../../../../config/api';
import { GLOBAL } from '../../../../config/global';
import { style } from '../../../../theme/style';
import { SearchInput } from '../../../../component/SearchInput.js';
import { PageStatusIndex } from '../../../../component/page-status/PageStatusIndex';
import { Common } from '../../../../component/common/Common';
import HTTP from '../../../../utils/http';
import ToastUtil from '../../../../utils/toast';
import StorageHelper from '../../../../utils/storageHelper';
import { Button } from '../../../../components/form/button';
import { STORAGE_CONSTANT } from '../../../../config/storage';

const scale = GLOBAL.SCALE;
const searchLeft = require('../../../../imgs/customer/searchLeft.png');

export class SeachSupplierPage extends Component {


	static navigationOptions = ({ navigation }) => {
		const params = navigation.state.params || {};
		console.log('params', params)
		return {
			headerTitle: (<SearchInput
				inputLeftIcon={searchLeft}
				setKeyWord={(txt) => { params.setKeyWord && params.setKeyWord(txt); }}
				onChangeText={() => { params.doSearch && params.doSearch(); }}
				onSubmitEditing={() => { params.editing && params.editing() }}
				onBlurFn={() => { params.editing && params.editing() }}
				placeholder={'搜索' + (params.orderType == 'P' ? '供应商' : '客户')}
			/>),
			headerLeft: <Common type="headLeft" onPress={() => { params.goBack && params.goBack() }} />,
			headerTintColor: style.color.dark,
			headerRight: (
				<Text onPress={() => { params.editing && params.editing() }} style={style.headTow.headerRight}>搜索</Text>
			),
			headerStyle: style.headTow.headerStyle,
			headerTitleStyle: style.headTow.headerTitleStyle
		}
	}
	//搜索value
	_setKeyWord = (txt) => {
		this.companyName = txt;//this.sendData.companyName = txt;
		this.searchCode = txt;
		if (!txt) {
			this.sendData.status = 'loading';
			this._isLoadRefresh();
		}
	}
	//监听输入框变化
	_doSearch = () => {
		console.log('监听');
	}
	//提交编辑
	_editing = () => {
		this._isLoadRefresh();
	}

	//返回
	_goBack = () => {
		let { params } = this.props.navigation.state;
		let { isSelect, orderType, companyId, callBack } = params;
		let { selectData } = this.state;
		if (isSelect && !selectData && !companyId) {
			ToastUtil.showWarning(orderType == 'P' ? '请选择一个供应商' : '请选择一个客户');
			return;
		}
		if (selectData) {
			callBack && callBack(selectData);
		}
		this.props.navigation.goBack();
	}

	constructor(props) {
		super(props);
		let { params } = props.navigation.state;
		let { choice } = params || {};
		let { corpId } = choice || {};
		this.isAgent = params.isAgent;
		this.orderType = params.orderType;
		this.companyName = params.companyName;
		this.deliveryType = params.deliveryType;
		this.companyId = params.companyId;
		this.companyIdBuy = params.companyIdBuy;
		this.queryType = params.queryType;
		this.type = params.type || false;
		this.code = params.code || null;
		this.isAll = params.isAll || false;
		this.newOrder = params.newOrder || false;
		this.sendData = {
			companyName: '',
			corpTypeList: params.orderType == 'P' ? ['1'] : ['2'],   // 1 供应商   2  客户
			pageNo: 1,
			status: 'loading',
			isForeign: params.isForeign ? params.isForeign : 0,
			orderType: params.orderType || '',
			bizMode: params.bizMode || '',
			corpId: corpId || ''
		}
		this.state = {
			sourceData: [],   // 列表数据
			selectData: null,  // 选中数据
			_isLoad: false,
		}
		this.pageNo = 1;
		this.totalPage = 1;
		this.onrefresh = false;  //加载为true 刷新为false
	}


	async	componentDidMount() {
		this.props.navigation.setParams({
			setKeyWord: this._setKeyWord,
			doSearch: this._doSearch,
			editing: this._editing,
			goBack: this._goBack
		});
		this.userInfo = await this._getUserInfo();
		this._getData();
	}

	_getUserInfo = async () => {
		//获取用户信息
		let userInfo = await StorageHelper.get(STORAGE_CONSTANT.USER_INFO_KEY);
		if (userInfo) {
			userInfo = JSON.parse(userInfo);
		}
		return userInfo || {};
	}

	// 获取数据
	async _getData() {
		this.setState({
			_isLoad: true
		})
		this.sendData.queryType = this.queryType;
		this.sendData.companyId = this.companyId;
		this.sendData.companyName = this.companyName;
		this.sendData.pageNo = this.pageNo;
		this.sendData.searchCode = this.searchCode || null;
		if (this.companyIdBuy) {
			this.sendData.companyIdList = [];
			this.sendData.companyIdList.push(this.companyIdBuy);
		}
		let URL = this.isAgent == 'Y' ? API_GENERATE(API.AGENT_GET_SUPPLIER) : API_GENERATE(API.GET_CUSTOMER_LIST);
		if (this.code == 'SX') {// 授信账单用
			URL = API_GENERATE(API.CREDIT_BILL_LIST_SX);
		} else if (this.code) {
			URL = API_GENERATE(API.CREDIT_BILL_LIST_ALL);
		}
		let responseData = await HTTP.POST(URL, this.sendData);
		if (responseData && responseData.rows.length > 0) {  // 数据存在
			let resList = responseData.rows;
			this.totalPage = responseData.totalPage;
			this.sendData.status = 'data';
			let newArr = responseData.rows.map((item, index) => {
				item.checked = false;
				// 新版去掉中化石化销售公司
				if (this.newOrder && item.companyId == this.userInfo.companyId) responseData.rows.splice(index, 1)
			})
			if (this.onrefresh) {// 加载
				this.setState({
					sourceData: this.state.sourceData.concat(responseData.rows),
					_isLoad: false
				})
			} else {// 刷新
				this.setState({
					sourceData: responseData.rows,
					_isLoad: false
				})
			}

		} else {  // 数据为空 或者 请求没响应
			this.sendData.status = 'empty';
			this.setState({
				sourceData: [],
				_isLoad: false
			})
		}
	}

	// 点击每一条 
	_itemFn = (itemStr) => {
		let { companyId } = itemStr;
		let { sourceData } = this.state;
		let lsArr = null;
		sourceData.map((item) => {
			if (companyId == item.companyId) {
				item.checked = !item.checked;
				if (item.checked) {
					lsArr = item
				}
			} else {
				item.checked = false;
			}
			return item;
		})
		this.setState({
			sourceData: sourceData,
			selectData: lsArr
		})
	}

	//提交回调
	_commitCall = () => {
		let { selectData } = this.state;
		let { isCreditExpired, isNotComplete, isFrozen, mdmCode } = selectData || {};  //this.type != 'address' 选择地址时候不控

		if (this.isAll) {  //新增订单控制
			if (isCreditExpired == '2' && this.type != 'SinoNewOrderBaseInfoPage') { //营业执照   0 正常，1 快过期，2 已过期   授信不受控制 加 !this.code
				ToastUtil.showWarning('企业营业执照已过期，无法交易')
				return
			}
			if (isNotComplete == '1' && this.type != 'SinoNewOrderBaseInfoPage') { // 信息不全   0 正常，1信息不全    授信不受控制 加 !this.code
				ToastUtil.showWarning('企业基础数据缺失，无法交易，请补充')
				return
			}
			if (isFrozen == 1) {
				ToastUtil.showWarning('冻结企业无法交易，若有疑问请联系风控部。')
				return
			}
			if (!mdmCode) {
				ToastUtil.showWarning('企业MDM码缺失，无法交易')
				return
			}
		}

		if (selectData) {
			if (this.props.navigation.state.params.callBack) {
				this.props.navigation.state.params.callBack(selectData);
			}
			if (this.type == "address") {
				this.props.navigation.navigate('DeliveryAddress', {
					orderType: this.orderType,
					companyName: selectData.companyName,
					deliveryType: this.deliveryType,
					companyId: selectData.companyId,
				});
			} else if (this.type) {
				this.props.navigation.goBack()
			}
		} else {
			ToastUtil.showWarning(this.props.navigation.state.params.orderType == 'P' ? '请选择一个供应商' : '请选择一个客户');
		}
	}

	// 下拉刷新
	_isLoadRefresh = () => {
		this.onrefresh = false;
		this.pageNo = 1;
		this._getData();
	}

	//上拉加载
	_loadData = () => {
		if (this.totalPage > this.pageNo) {
			this.onrefresh = true;
			this.pageNo++;
			this._getData();
		}
	}


	//返回一条数据模板itemView
	_renderItemView = (customer) => {
		let rightImg = require('../../../../imgs/global/success.png');
		let emptyImg = require('../../../../imgs/global/option.png');
		let lockImg = require('../../../../imgs/order/lock.png');
		let { companyName, corpType, isCredited, checked, isFrozen } = customer.item;
		return (
			<TouchableOpacity onPress={() => { this._itemFn(customer.item) }}>
				<View style={styles.listItem}>
					<View style={styles.hang}>
						<Image style={styles.office} source={require('../../../../imgs/customer/office.png')} />
						<View>
							<View style={styles.textRow}>
								<Text style={styles.title}>{companyName}</Text>
								{
									isFrozen ? <Image style={styles.isfrozen} source={lockImg} /> : null
								}
								{
									isCredited == '1' ? (<Text style={styles.iconText}>信</Text>) : null
								}
							</View>
						</View>
					</View>
					{
						checked ? (<Image style={styles.bombImg} source={rightImg} />) : (<Image style={styles.bombImg} source={emptyImg} />)
					}
				</View>
			</TouchableOpacity>
		);
	}

	render() {
		let { sourceData, _isLoad } = this.state;
		return (
			<View style={styles.container}>
				{
					this.sendData.status == 'data' ? (
						<View style={styles.conBox}>
							<FlatList
								extraData={this.state}
								data={sourceData}
								renderItem={this._renderItemView}
								refreshing={_isLoad}
								onRefresh={() => { this._isLoadRefresh() }}
								onEndReachedThreshold={0.1}
								onEndReached={() => { this._loadData() }}
							/>
							{/* <Common type="bottom" title="提交" callBack={this._commitCall} /> */}
							<View style={styles.btnWarp}>
								<Button text={'添加'} width={300} height={34} onPress={this._commitCall} />
							</View>
						</View>
					) : (<PageStatusIndex status={this.sendData.status} />)
				}
			</View >
		)
	}
}


const styles = StyleSheet.create({
	container: {
		flex: 1,
		backgroundColor: style.color.bgGray,
	},
	conBox: {
		marginTop: 12 * scale,
		flex: 1,
		backgroundColor: style.color.white,
	},
	listItem: {
		borderBottomWidth: 1 / PixelRatio.get(),
		borderStyle: 'solid',
		borderBottomColor: style.color.gray,
		paddingLeft: 15 * scale,
		paddingRight: 30 * scale,
		flexDirection: 'row',
		justifyContent: 'space-between',
		height: 72 * scale,
		alignItems: 'center'
	},
	office: {
		width: 44 * scale,
		height: 44 * scale,
		marginRight: 13 * scale
	},
	bombImg: {
		width: 14 * scale,
		height: 14 * scale,
		justifyContent: 'flex-end'
	},
	textRow: {
		flexDirection: 'row',
		alignItems: 'center',
		width: 270 * scale,
	},
	title: {
		fontSize: 14 * scale,
		color: style.color.normal,
		paddingRight: 5 * scale,
	},
	iconText: {
		height: 18 * scale,
		lineHeight: 16 * scale,
		fontSize: 12 * scale,
		color: style.color.white,
		backgroundColor: style.color.button,
		paddingLeft: 3 * scale,
		paddingRight: 3 * scale,
		borderRadius: 4 * scale
	},
	hang: {
		flexDirection: 'row',
		alignItems: 'center'
	},
	element: {
		borderWidth: 1 / PixelRatio.get(),
		borderStyle: 'solid',
		borderColor: '#E9E9E9',
		backgroundColor: '#F4F4F4',
		fontSize: 12 * scale,
		color: style.color.darkGray,
		borderRadius: 4 * scale,
		height: 18 * scale,
		lineHeight: 16 * scale,
		paddingLeft: 5 * scale,
		paddingRight: 5 * scale,
		flexDirection: 'row',
		marginRight: 8 * scale
	},
	hangTwo: {
		marginTop: 5 * scale,
		flexDirection: 'row',
		flexWrap: 'wrap',
	},
	isfrozen: {
		marginRight: 5 * scale,
		width: 20 * scale,
		height: 20 * scale,
	},
	btnWarp: {
		height: 72 * scale,
		flexDirection: 'row',
		alignItems: 'center',
		justifyContent: 'center',
	},
})